﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Daemon.Common
{
	public static class GenerateOrderNo
	{
		private static object obj = new object();
		private static int GuidInt { get { return Guid.NewGuid().GetHashCode(); } }
		private static string GuidIntStr { get { return Math.Abs(GuidInt).ToString(); } }

		/// <summary>
		/// 生成
		/// </summary>
		/// <param name="mark">前缀</param>
		/// <param name="timeType">时间精确类型  1 日,2 时,3 分，4 秒,5毫秒(默认) </param>
		/// <param name="id">id 小于或等于0则随机生成id</param>
		/// <returns></returns>
		public static string Gener(string orderNo, string mark, int timeType = 5, int id = 1)
		{
			lock (obj)
			{
				var number = mark;
				var ticks = (DateTime.Now.Ticks - GuidInt).ToString();
				int fillCount = 0;//填充位数

				number += GetTimeStr(timeType, out fillCount);
				if (!string.IsNullOrWhiteSpace(orderNo))
				{
					var numberNo = orderNo.Substring(25);
					if (numberNo.Length > 3)
					{
						number += $"{ticks.Substring(ticks.Length - (fillCount + 3))}{(long.Parse(numberNo) + 1)}";
					}
					else
					{
						int count = numberNo.Count(x => x == '0');
						var str = (long.Parse(numberNo) + 1).ToString();
						str = str.PadLeft(count == 1 ? count + 2 : count + 1, '0');

						number += $"{ticks.Substring(ticks.Length - (fillCount + 3))}{str}";
					}
				}
				else if (id > 0)
				{
					//number += ticks.Substring(ticks.Length - (fillCount + 3)) + id.ToString().PadLeft(10, '0');
					number += $"{ticks.Substring(ticks.Length - (fillCount + 3))}{id.ToString().PadLeft(3, '0')}";
				}
				else
				{
					number += ticks.Substring(ticks.Length - (fillCount + 3)) + GuidIntStr.PadLeft(3, '0');
				}

				return number;
			}
		}

		public static string GeneratePickUpCode()
		{
			Random random = new Random();
			const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			const string digits = "0123456789";

			// 首位字母
			char firstLetter = letters[random.Next(letters.Length)];

			// 后面的5位数字
			string numbers = new string(Enumerable.Repeat(digits, 5)
				.Select(s => s[random.Next(s.Length)]).ToArray());

			// 合并生成的字符
			string code = firstLetter + numbers;
			return code;
		}

		/// <summary>
		/// 获取时间字符串
		/// </summary>
		/// <param name="timeType">时间精确类型  1 日,2 时,3 分，4 秒(默认)</param>
		/// <param name="fillCount">填充位数</param>
		/// <returns></returns>
		private static string GetTimeStr(int timeType, out int fillCount)
		{
			var time = DateTime.Now;
			if (timeType == 1)
			{
				fillCount = 6;
				return time.ToString("yyyyMMdd");
			}
			else if (timeType == 2)
			{
				fillCount = 4;
				return time.ToString("yyyyMMddHH");
			}
			else if (timeType == 3)
			{
				fillCount = 2;
				return time.ToString("yyyyMMddHHmm");
			}
			else if (timeType == 4)
			{
				fillCount = 0;
				return time.ToString("yyyyMMddHHmmss");
			}
			else
			{
				fillCount = 0;
				return time.ToString("yyyyMMddHHmmssffff");
			}
		}
	}
}

